package com.yk.satoken.demos.minio.util;

import cn.hutool.core.util.StrUtil;
import com.yk.satoken.demos.minio.util.ServletUtil;
import lombok.Cleanup;
import org.springframework.http.MediaTypeFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public class FileDownloadUtil {

    /**
     * 下载文件
     *
     * @param bytes
     * @param fileName 订单信息.pdf
     */
    public static void downloadFile(byte[] bytes, String fileName, String downName) {
        if (StrUtil.isNotEmpty(downName)) {
            fileName = downName;
        }
        HttpServletResponse response = ServletUtil.getResponse();
        HttpServletRequest request = ServletUtil.getRequest();
        try {
            @Cleanup InputStream is = new ByteArrayInputStream(bytes);
            @Cleanup BufferedInputStream bis = new BufferedInputStream(is);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/plain");
            // 判断文件下载的类型
            String contentType = getFileType(fileName);
            // 编码的文件名字,关于中文乱码的改造
            String codeFileName = "";
            String agent = request.getHeader("USER-AGENT").toLowerCase();
            if (-1 != agent.indexOf("msie") || -1 != agent.indexOf("trident")) {
                // IE
                codeFileName = URLEncoder.encode(fileName, "UTF-8");
            } else if (-1 != agent.indexOf("mozilla")) {
                // 火狐，谷歌
                codeFileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } else {
                codeFileName = URLEncoder.encode(fileName, "UTF-8");
            }
            response.setContentType(contentType);
            // 设置HTTP响应的头部信息，用于告诉浏览器将响应的内容作为附件下载，并指定下载的文件名。其中，codeFileName 是要下载的文件名。
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(codeFileName.getBytes(), "utf-8"));
            @Cleanup OutputStream os = response.getOutputStream();
            int i;
            byte[] buff = new byte[1024 * 8];
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 显示文件
     */
    public static void flushImage(byte[] bytes) {
        flushImage(bytes, null);
    }


    /**
     * 显示文件
     */
    public static void flushImage(byte[] bytes, String fileName) {
        try {
            @Cleanup OutputStream outputStream = null;
            @Cleanup InputStream in = null;
            // 设置图片类型
            if (fileName != null && MediaTypeFactory.getMediaType(fileName).isPresent()) {
                ServletUtil.getResponse().setContentType(MediaTypeFactory.getMediaType(fileName).get().toString());
            }
            // 读取指定路径下面的文件
            in = new ByteArrayInputStream(bytes);
            outputStream = new BufferedOutputStream(ServletUtil.getResponse().getOutputStream());
            // 创建存放文件内容的数组
            byte[] buff = new byte[1024];
            // 所读取的内容使用n来接收
            int n;
            // 当没有读取完时,继续读取,循环
            while ((n = in.read(buff)) != -1) {
                // 将字节数组的数据全部写入到输出流中
                outputStream.write(buff, 0, n);
            }
            // 强制将缓存区的数据进行输出
            outputStream.flush();
        } catch (Exception e) {
            e.getMessage();
        }
    }

    private static String getFileType(String fileName) {
        String contentType = "";

        if (fileName.endsWith(".png")) {
            contentType = "image/png";
        } else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
            contentType = "image/jpeg";
        } else if (fileName.endsWith(".gif")) {
            contentType = "image/gif";
        } else if (fileName.endsWith(".bmp")) {
            contentType = "image/bmp";
        } else if (fileName.endsWith(".webp")) {
            contentType = "image/webp";
        } else if (fileName.endsWith(".ico")) {
            contentType = "image/x-icon";
        } else if (fileName.endsWith(".svg")) {
            contentType = "image/svg+xml";
        } else if (fileName.endsWith(".tiff") || fileName.endsWith(".tif")) {
            contentType = "image/tiff";
        } else if (fileName.endsWith(".eps")) {
            contentType = "application/postscript";
        } else if (fileName.endsWith(".raw")) {
            contentType = "image/raw";
        } else if (fileName.endsWith(".psd")) {
            contentType = "application/photoshop";
        } else if (fileName.endsWith(".ai")) {
            contentType = "application/illustrator";
        } else if (fileName.endsWith(".indd")) {
            contentType = "application/indesign";
        } else if (fileName.endsWith(".pdf")) {
            contentType = "application/pdf";
        } else if (fileName.endsWith(".doc") || fileName.endsWith(".docx")) {
            contentType = "application/msword";
        } else if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
            contentType = "application/vnd.ms-excel";
        } else if (fileName.endsWith(".ppt") || fileName.endsWith(".pptx")) {
            contentType = "application/vnd.ms-powerpoint";
        } else if (fileName.endsWith(".txt")) {
            contentType = "text/plain";
        } else if (fileName.endsWith(".html")) {
            contentType = "text/html";
        } else if (fileName.endsWith(".css")) {
            contentType = "text/css";
        } else if (fileName.endsWith(".js")) {
            contentType = "application/javascript";
        } else if (fileName.endsWith(".json")) {
            contentType = "application/json";
        } else if (fileName.endsWith(".xml")) {
            contentType = "application/xml";
        } else if (fileName.endsWith(".zip")) {
            contentType = "application/zip";
        } else if (fileName.endsWith(".rar")) {
            contentType = "application/x-rar-compressed";
        } else if (fileName.endsWith(".tar")) {
            contentType = "application/x-tar";
        } else if (fileName.endsWith(".gz")) {
            contentType = "application/gzip";
        } else if (fileName.endsWith(".7z")) {
            contentType = "application/x-7z-compressed";
        } else if (fileName.endsWith(".mp3")) {
            contentType = "audio/mpeg";
        } else if (fileName.endsWith(".wav")) {
            contentType = "audio/wav";
        } else if (fileName.endsWith(".ogg")) {
            contentType = "audio/ogg";
        } else if (fileName.endsWith(".flac")) {
            contentType = "audio/flac";
        } else if (fileName.endsWith(".aac")) {
            contentType = "audio/aac";
        } else if (fileName.endsWith(".m4a")) {
            contentType = "audio/mp4";
        } else if (fileName.endsWith(".wma")) {
            contentType = "audio/x-ms-wma";
        } else if (fileName.endsWith(".avi")) {
            contentType = "video/x-msvideo";
        } else if (fileName.endsWith(".mov")) {
            contentType = "video/quicktime";
        } else if (fileName.endsWith(".mp4")) {
            contentType = "video/mp4";
        } else if (fileName.endsWith(".mkv")) {
            contentType = "video/x-matroska";
        } else if (fileName.endsWith(".flv")) {
            contentType = "video/x-flv";
        } else if (fileName.endsWith(".wmv")) {
            contentType = "video/x-ms-wmv";
        } else if (fileName.endsWith(".swf")) {
            contentType = "application/x-shockwave-flash";
        } else if (fileName.endsWith(".exe")) {
            contentType = "application/x-msdownload";
        } else if (fileName.endsWith(".dll")) {
            contentType = "application/octet-stream";
        } else if (fileName.endsWith(".so")) {
            contentType = "application/octet-stream";
        } else if (fileName.endsWith(".o")) {
            contentType = "application/octet-stream";
        } else if (fileName.endsWith(".obj")) {
            contentType = "application/octet-stream";
        } else if (fileName.endsWith(".lib")) {
            contentType = "application/octet-stream";
        } else if (fileName.endsWith(".a")) {
            contentType = "application/octet-stream";
        } else if (fileName.endsWith(".class")) {
            contentType = "application/octet-stream";
        } else if (fileName.endsWith(".jar")) {
            contentType = "application/java-archive";
        } else if (fileName.endsWith(".war")) {
            contentType = "application/java-archive";
        } else if (fileName.endsWith(".ear")) {
            contentType = "application/java-archive";
        } else if (fileName.endsWith(".sar")) {
            contentType = "application/java-archive";
        } else if (fileName.endsWith(".apk")) {
            contentType = "application/vnd.android.package-archive";
        } else if (fileName.endsWith(".ipa")) {
            contentType = "application/vnd.iphone";
        } else if (fileName.endsWith(".app")) {
            contentType = "application/x-app";
        } else if (fileName.endsWith(".msi")) {
            contentType = "application/x-msi";
        } else if (fileName.endsWith(".msp")) {
            contentType = "application/x-ms-manifest";
        } else if (fileName.endsWith(".mst")) {
            contentType = "application/x-ms-manifest";
        } else if (fileName.endsWith(".idl")) {
            contentType = "text/plain";
        } else if (fileName.endsWith(".mid")) {
            contentType = "audio/midi";
        } else if (fileName.endsWith(".midi")) {
            contentType = "audio/midi";
        } else if (fileName.endsWith(".kar")) {
            contentType = "audio/midi";
        } else if (fileName.endsWith(".mp3")) {
            contentType = "audio/mpeg";
        } else if (fileName.endsWith(".ogg")) {
            contentType = "audio/ogg";

        }
        return contentType;
    }
}
